package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApi2Service;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.HuiYuanUtil;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.datapush.service.apipush.utils.ZhenXiangMaskApisUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 *  全授权
 */
@Service
public class HuiYuanApiSMaskPushService implements IPushApiService,IPushApi2Service {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("mobileYm", memberSourceInfo.getMobile().substring(0,8));
        paramMap.put("idCard", memberSourceInfo.getIdcard());
        paramMap.put("realName", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", 1);
        }else {
            paramMap.put("sex", 2);
        }
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("province",memberSourceInfo.getProvince());
        paramMap.put("provinceCode",memberSourceInfo.getProvinceCode());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("huabei", HuiYuanUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("shebao",HuiYuanUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("baitiao",HuiYuanUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        paramMap.put("yuqi",HuiYuanUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("house",HuiYuanUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("baodan",HuiYuanUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("car",HuiYuanUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("gjj",HuiYuanUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("zhimaScore",HuiYuanUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("outOrderNo", orderNo);
        paramMap.put("userIp", memberSourceInfo.getReqIp());
        if(StrUtil.equals(memberSourceInfo.getGongzuo(),"gz002")){
            paramMap.put("enterpriseOwner", "eo002");
        }else {
            paramMap.put("enterpriseOwner", "eo001");
        }

        //加密
        String encrypt =  SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSONObject.toJSONString(paramMap));

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("tranData",encrypt);
        bizMap.put("requestNo", UUID.randomUUID().toString());
        bizMap.put("channelCode",pushApiKeyParam.getApiCode());

        log.info("【汇元全流程导量】 掩码撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【汇元全流程导量】 掩码撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("status");
        String respMsg = resultObject.getString("message");
        JSONObject data = resultObject.getJSONObject("data");

        pushApiResult.setCode(respCode);
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);
        if (!StrUtil.equals(respCode, "000")) {
            pushApiResult.setPushSuccess(false);
            return pushApiResult;
        }

        String logo = data.getString("logo");
        String productName = data.getString("productName");
        String orgName = data.getString("companyName");
        String productId = data.getString("orderNo");
        String outOrderNo = data.getString("outOrderNo");
        extJson.put("productId",orderNo);
        // 撞库成功之后，商户的机构数据存储
        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
        thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
        thirdInfoDTO.setOrderNo(orderNo);
        JSONObject infoObject = new JSONObject();
        infoObject.put("productName",productName);
        infoObject.put("orderNo",orderNo);
        infoObject.put("productId",outOrderNo);
        infoObject.put("companyName",orgName);
        infoObject.put("companyLogo",logo);
        infoObject.put("maxLoanAmount","200000");
        infoObject.put("maxLoanRate","20");
        infoObject.put("minLoanRate","1");
        infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
        JSONArray jsonArray = new JSONArray();
        JSONArray protocolList = data.getJSONArray("protocolList");
        if (protocolList.size() != 0){
            for (Object o : protocolList) {
                JSONObject jsonObject1 = new JSONObject();
                String s = JSONObject.toJSONString(o);
                JSONObject jsonObject = JSON.parseObject(s);
                String protocolName = jsonObject.getString("protocolName");
                String protocolUrl = jsonObject.getString("protocolUrl");
                jsonObject1.put("protocalName",protocolName);
                jsonObject1.put("protocalUrl",protocolUrl);
                jsonArray.add(jsonObject1);
            }
        }
        infoObject.put("protocalList",jsonArray);
        thirdInfoDTO.setInfoObject(infoObject);

        // 撞库成功之后，商户的机构数据存储

        JSONArray md5List = data.getJSONArray("md5List");
        String mobileMd5 = memberSourceInfo.getMobileMd5();
        if(MobileMd5IsInListUtils.isMobileMd5InList(md5List,mobileMd5)){
            //如果存在
            pushApiResult.setPushSuccess(false);
            pushApiResult.setCode(respCode+ "|" + "500");
            pushApiResult.setMessage(respMsg + "|" + mobileMd5 +"已存在");
            return pushApiResult;
        }


        //进行分润操作
        String priceType = pushApiKeyParam.getPriceType();
        BigDecimal typeRate = pushApiKeyParam.getTypeRate();
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
            BigDecimal price = data.getBigDecimal("price");//下游返回分润前价格
            if (price == null || price.compareTo(new BigDecimal(0.00)) == -1){
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            BigDecimal priceRight = typeRate.multiply(price);//分润后价格
            pushApiResult.setPrice(price);
            pushApiResult.setPriceRight(priceRight);

        }

        boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
        if (save){
            pushApiResult.setPushSuccess(true);
            extJson.put("orderNo",productId);
        }else{
            pushApiResult.setMessage("保存撞库数据失败");
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        String orderNo1 = extJson.getString("orderNo");
        String queryUrl = pushApiKeyParam.getRegisterUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("mobile", memberSourceInfo.getMobile());
        paramMap.put("mobileMd5", memberSourceInfo.getMobileMd5());
        paramMap.put("idCard", memberSourceInfo.getIdcard());
        paramMap.put("realName", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", 1);
        }else {
            paramMap.put("sex", 2);
        }
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("province",memberSourceInfo.getProvince());
        paramMap.put("provinceCode",memberSourceInfo.getProvinceCode());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("huabei", HuiYuanUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("shebao",HuiYuanUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("baitiao",HuiYuanUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        paramMap.put("yuqi",HuiYuanUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("house",HuiYuanUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("baodan",HuiYuanUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("car",HuiYuanUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("gjj",HuiYuanUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("zhimaScore",HuiYuanUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("orderNo", orderNo1);
        paramMap.put("userIp", memberSourceInfo.getReqIp());
        if(StrUtil.equals(memberSourceInfo.getGongzuo(),"gz002")){
            paramMap.put("enterpriseOwner", "eo002");
        }else {
            paramMap.put("enterpriseOwner", "eo001");
        }

        //加密
        String encrypt =  SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSONObject.toJSONString(paramMap));

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("tranData",encrypt);
        bizMap.put("requestNo", UUID.randomUUID().toString());
        bizMap.put("channelCode",pushApiKeyParam.getApiCode());

        log.info("【汇元全流程导量】 掩码导量开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【汇元全流程导量】 掩码导量结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("status");
        String respMsg = resultObject.getString("message");
        JSONObject data = resultObject.getJSONObject("data");

        pushApiResult.setCode(respCode );
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(respCode );
        thirdInfoDTO.setRetMsg(respMsg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (StrUtil.equals(String.valueOf(respCode), "000")) {
                thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);

        if (StrUtil.equals(String.valueOf(respCode), "000")) {
                //修改时间
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }


    @Override
    public PushApiResult checkUserCode(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("mobileYm", memberSourceInfo.getMobile().substring(0, 8));
        paramMap.put("idCard", memberSourceInfo.getIdcard());
        paramMap.put("realName", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1) {
            paramMap.put("sex", 1);
        } else {
            paramMap.put("sex", 2);
        }
        paramMap.put("age", memberSourceInfo.getAge());
        paramMap.put("province", memberSourceInfo.getProvince());
        paramMap.put("provinceCode", memberSourceInfo.getProvinceCode());
        paramMap.put("city", memberSourceInfo.getCity());
        paramMap.put("cityCode", memberSourceInfo.getCityCode());
        paramMap.put("huabei", HuiYuanUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("shebao", HuiYuanUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("baitiao", HuiYuanUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        paramMap.put("yuqi", HuiYuanUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("house", HuiYuanUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("baodan", HuiYuanUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("car", HuiYuanUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("gjj", HuiYuanUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("zhimaScore", HuiYuanUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("outOrderNo", orderNo);
        paramMap.put("userIp", memberSourceInfo.getReqIp());
        if (StrUtil.equals(memberSourceInfo.getGongzuo(), "gz002")) {
            paramMap.put("enterpriseOwner", "eo002");
        } else {
            paramMap.put("enterpriseOwner", "eo001");
        }

        //加密
        String encrypt = SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSONObject.toJSONString(paramMap));

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("tranData", encrypt);
        bizMap.put("requestNo", UUID.randomUUID().toString());
        bizMap.put("channelCode", pushApiKeyParam.getApiCode());

        log.info("【汇元全流程导量】 掩码撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【汇元全流程导量】 掩码撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("status");
        String respMsg = resultObject.getString("message");
        JSONObject data = resultObject.getJSONObject("data");

        pushApiResult.setCode(respCode);
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);
        if (!StrUtil.equals(respCode, "000")) {
            pushApiResult.setPushSuccess(false);
            return pushApiResult;
        }

        String logo = data.getString("logo");
        String productName = data.getString("productName");
        String orgName = data.getString("companyName");
        String productId = data.getString("orderNo");
        String outOrderNo = data.getString("outOrderNo");
        extJson.put("productId", orderNo);
        // 撞库成功之后，商户的机构数据存储
        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
        thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
        thirdInfoDTO.setOrderNo(orderNo);
        JSONObject infoObject = new JSONObject();
        infoObject.put("productName", productName);
        infoObject.put("orderNo", orderNo);
        infoObject.put("productId", outOrderNo);
        infoObject.put("companyName", orgName);
        infoObject.put("companyLogo", logo);
        infoObject.put("maxLoanAmount", "200000");
        infoObject.put("maxLoanRate", "20");
        infoObject.put("minLoanRate", "1");
        infoObject.put("businessInfo", pushApiKeyParam.getInfoName());
        JSONArray jsonArray = new JSONArray();
        JSONArray protocolList = data.getJSONArray("protocolList");
        if (protocolList.size() != 0) {
            for (Object o : protocolList) {
                JSONObject jsonObject1 = new JSONObject();
                String s = JSONObject.toJSONString(o);
                JSONObject jsonObject = JSON.parseObject(s);
                String protocolName = jsonObject.getString("protocolName");
                String protocolUrl = jsonObject.getString("protocolUrl");
                jsonObject1.put("protocalName", protocolName);
                jsonObject1.put("protocalUrl", protocolUrl);
                jsonArray.add(jsonObject1);
            }
        }
        infoObject.put("protocalList", jsonArray);
        thirdInfoDTO.setInfoObject(infoObject);

        // 撞库成功之后，商户的机构数据存储

        JSONArray md5List = data.getJSONArray("md5List");
        pushApiResult.setMd5List(md5List);

        //进行分润操作
        String priceType = pushApiKeyParam.getPriceType();
        BigDecimal typeRate = pushApiKeyParam.getTypeRate();
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)) {
            BigDecimal price = data.getBigDecimal("price");//下游返回分润前价格
            if (price == null || price.compareTo(new BigDecimal(0.00)) == -1) {
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            BigDecimal priceRight = typeRate.multiply(price);//分润后价格
            pushApiResult.setPrice(price);
            pushApiResult.setPriceRight(priceRight);

        }

        boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
        if (save) {
            pushApiResult.setPushSuccess(true);
            extJson.put("orderNo", productId);
        } else {
            pushApiResult.setMessage("保存撞库数据失败");
        }

        return pushApiResult;
    }

}
